package cn.daixi.web.common.advice;

import cn.daixi.web.common.dto.ErrorRes;
import cn.daixi.web.common.exception.ValidateException;
import cn.hutool.core.util.ArrayUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 基础异常
     */
    @ExceptionHandler(ValidateException.class)
    public ResponseEntity<ErrorRes> baseException(ValidateException e) {
        ErrorRes errorRes = new ErrorRes();
        errorRes.setMessage(e.getMessage());
        errorRes.setCode(e.getCode());
        return ResponseEntity.status(400).body(errorRes );
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorRes> errorResult( MethodArgumentNotValidException exception) {

        ErrorRes<Map<String, Object>> errorRes = new ErrorRes<>();
        ArrayList<String> arrayList = new ArrayList<>();
        Map<String, Object> response = new HashMap<>();
        BindingResult bindingResult = exception.getBindingResult();
        if (bindingResult.hasErrors()) {
            bindingResult.getAllErrors().forEach(error -> {
                String fieldName = ((FieldError) error).getField();
                String errorMessage = error.getDefaultMessage();
                response.put(fieldName, errorMessage);
                arrayList.add(errorMessage);
            });
        }
        errorRes.setMessage(ArrayUtil.join(arrayList.toArray(),","));
        errorRes.setData(response);
        // 调试时返回详细错误信息
        return ResponseEntity.status(400).body(errorRes );
    }
}
